/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package seminario.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.apache.commons.io.IOUtils;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author bpmlab
 */
public class UploadUtil implements Serializable {
    
    public static final String PATH = "/resources/arquivos";
    
    public static String contextPath(String fileName) {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext external = context.getExternalContext();
        String path = external.getRealPath(
                PATH
                + File.separator
                + fileName);
        return path;
    }
    
    public static boolean copiarParaArquivos(UploadedFile file) {
        try {
            String path = contextPath(file.getFileName());
            FileOutputStream saida = new FileOutputStream(path);
            InputStream entrada = file.getInputstream();
            IOUtils.copy(entrada, saida);
            IOUtils.closeQuietly(saida);
            IOUtils.closeQuietly(entrada);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
    
    public static byte[] upload(UploadedFile file) {
        try {
            return IOUtils.toByteArray(file.getInputstream());
        } catch (IOException ex) {
            return null;
        }
    }
}
